using System;
using System.Data;
using System.Data.SqlClient;
using CoreLibrary.Sql;

namespace CoreLibrary.Messaging.Sql {

    public class GetMessage : ISqlQuery<Message> {

        private readonly string _tableName;
        private readonly string _messageId;

        public GetMessage(string tableName, string messageId) {
            _tableName = tableName;
            _messageId = messageId;
        }

        public string GetSQL() {
            return string.Format(@"
                select *
                from {0}
                where id = @id
            ", _tableName);
        }

        public void SetParameters(SqlCommand command) {
            command.Parameters.Add("@id", SqlDbType.UniqueIdentifier).Value = new Guid(_messageId);
        }

        public Message GetResult(SqlConnection conn, SqlDataReader result) {
            if (result.HasRows) {
                while (result.Read()) {
                    return ReadMessage(result);
                }
            }
            return null;
        }

        public static Message ReadMessage(SqlDataReader result) {
            return new Message {
                Id = result["id"].ToString(),
                ApplicationId = Util.GetInt(result["aid"], 0),
                Data = (string)result["body"],
                Status = (MessageStatus)result["status"],
                Fault = (string)result["fault"],
                Retry = (int) result["retry"],
                DateCreated = ((DateTime)result["date_created"]),
                DateScheduled = ((DateTime)result["date_scheduled"])
           };
        }
    }
}